package com.lxk.service.event.handler;

import com.lxk.common.EventTypeEnum;
import com.lxk.common.GsonUtils;
import com.lxk.dao.es.BlogEsDao;
import com.lxk.domain.BlogBackupEntity;
import com.lxk.domain.es.BlogEsEntity;
import com.lxk.service.event.AbstractEventHandler;
import com.lxk.service.event.domain.EventDto;
import com.lxk.utils.TraceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;

/**
 * Created by Lxk on 2020/7/25.
 */
@Component
public class BlogPubEventHandler extends AbstractEventHandler<EventDto> {

    private static final Logger logger = LoggerFactory.getLogger(BlogPubEventHandler.class);

    @Autowired
    private BlogEsDao blogEsDao;

    @Override
    public List<EventTypeEnum> supports() {
        return Arrays.asList(EventTypeEnum.EVENT_BLOG_PUBLISH);
    }

    @Override
    public boolean handleEvent(EventDto eventDto) {
        TraceUtil.genTrace("blog_pub_event");
        BlogEsEntity blogEsEntity = GsonUtils.getGson().fromJson(eventDto.getContent(),BlogEsEntity.class);
        try {
            blogEsDao.deleteById(blogEsEntity.getId());
            //正文内容均不为空，执行保存操作
            if(!StringUtils.isEmpty(blogEsEntity.getTitle())
                &&!StringUtils.isEmpty(blogEsEntity.getDesc())
                &&!StringUtils.isEmpty(blogEsEntity.getContent())){
                blogEsEntity = blogEsDao.save(blogEsEntity);
            }
            logger.info("博客更新同步保存ES blogEsEntity:{}",blogEsEntity);
        } catch (Exception e) {
            logger.error("ElasticSearch存储备份异常 :: eventDto:{}",eventDto, e);
            return false;
        }
        throw new RuntimeException("test");
    }

    @Override
    public boolean isFailedRetry() {
        return false;
    }

    @Override
    public Class<EventDto> eventType() {
        return EventDto.class;
    }

}
